<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model_" :rules="validatorRules" slot="detail">
        <a-row v-if="title === '导出'">
          <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
            <a-radio-group v-model="model_.type">
              <a-radio :value="1">系统生成MSKU</a-radio>
              <span style="margin-right: 10px;" v-if="model_.type === 1">
                导出：<a-input-number :min="0" :precision="0" v-model="model_.exportCount"/> 条
              </span>
              <a-radio :value="2">自己关联的MSKU产品</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="选择要导出的产品图片" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" prop="skuImageId" style="display: flex; flex-direction: column;">
            <div class="export-img" v-if="productImg && productImg.length">
              <a-checkbox-group v-model="model_.skuImageId">
                <a-checkbox :value="item.id" v-for="(item, index) in productImg" :key="item.id">
                  <img :src="item.imageUrl" @click="handleImg(item.imageUrl)">
                  <p style="width: 80px;">{{ item.imageUrl && item.imageUrl.split('/') && item.imageUrl.split('/').pop() && item.imageUrl.split('/').pop().slice(-10)}}</p>
                </a-checkbox>
              </a-checkbox-group>
            </div>
            <div v-else style="width: 100%;margin-top: 20px;">
              <a-empty description="暂无数据" />
            </div>
          </a-form-model-item>
        </a-row>
        <a-row v-else-if="title === '违规标记'">
          <a-col :span="24">
            <a-form-model-item label="违规星级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="level">
              <a-rate allow-half v-model="model_.level" />
            </a-form-model-item>
            <a-form-model-item label="违规标签" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="tagId">
              <j-search-select-tag type="list" v-model="model_.tagId" :dictOptions="tagOptions" placeholder="请选择违规标签" />
            </a-form-model-item>
            <a-form-model-item label="违规原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reason">
              <a-textarea v-model="model_.reason" rows="3" placeholder="请输入违规原因" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-else-if="title === '备注'">
          <a-col :span="24">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 }}" prop="remark">
              <a-textarea v-model="model_.remark" rows="3" placeholder="请输入备注内容" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-else-if="title === 'MSKU列表'">
          <a-table
            ref="table"
            size="middle"
            :scroll="{x:true}"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            class="j-table-force-nowrap"
            @change="handleTableChange">
            <span slot="action" slot-scope="text, record">
              <a @click="handleEdit(record)">编辑</a>
            </span>
          </a-table>
        </a-row>
        <a-row v-else-if="title === '上传视频'">
          <a-col :span="24">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 }}" prop="video">
              <j-upload-oss v-model="model_.video" fileType="video" bizPath="product" class="video-custom"></j-upload-oss>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-else-if="title === '下载视频'">
          <a-col :span="24">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 }}" prop="video">
              <a-radio-group v-model="checkedList" class="download-video">
                <j-upload-oss v-model="model_.video" fileType="video" bizPath="product" class="video-custom" disabled>
                  <template slot="customVideo" slot-scope="{ record }">
                    <a-radio :value="record.url"></a-radio>
                  </template>
                </j-upload-oss>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>

    <a-modal v-model="mskuObj.visible" title="编辑" @ok="handleOk">
      <a-row>
        <a-col :span="24">
          <a-form-model-item label="SKU" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sku">
            <a-input v-model.trim="mskuObj.record.sku" placeholder="请输入SKU" disabled ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item label="MSKU" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="msku">
            <a-input v-model.trim="mskuObj.record.msku" placeholder="请输入MSKU"  ></a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-modal>
  </a-spin>
</template>

<script>
  import { httpAction, getAction, putAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  export default {
    name: 'ProductLibrarySkuExportForm',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      title: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        disableMixinCreated: true,
        model: {},
        model_: {},
        productImg: [],
        tagOptions: [],
        checkedList: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        mskuObj: {
          visible: false,
          record: {}
        },
        validatorRules: {
          type: [
            { required: true, message: '请选择导出方式！' }
          ],
          skuImageId: [
            { required: true, message: '请选择图片！' }
          ],
          level: [
            { required: true, message: '请选择违规星级！' }
          ],
          tagId: [
            { required: true, message: '请选择违规标签！' }
          ],
          remark: [
            { required: true, message: '请输入备注内容！' }
          ]
        },
        // 表头
        columns: [
          {
            title:'MSKU',
            align:"center",
            dataIndex: 'msku',
          },
          {
            title:'绑定时间',
            align:"center",
            dataIndex: 'createTime',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          exportSKU: "/hzkj-product/product/productLibrary/sku/exportSKU",
          queryBySkuId: "/hzkj-product/product/productLibrary/skuImage/queryBySkuId",
          updateRemark: "/hzkj-product/product/productLibrary/sku/updateRemark",
          uploadVideo: "/hzkj-product/product/productLibrary/sku/uploadVideo",
          violationMark: "/hzkj-product/product/productLibrary/sku/violationMark",
          tagList: "/hzkj-product/product/productLibrary/tag/list",
          list: "/hzkj-product/product/productLibrary/skuMsku/list",
          productLibrarySkuMskuEdit: "/hzkj-product/product/productLibrary/skuMsku/edit"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      if(this.title === '违规标记'){
        this.getTagList();
      }
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        if(this.model.id){
          if(this.title === 'MSKU列表'){
            this.productLibrarySkuMskuList();
          }
          if(this.title === '导出'){
            this.queryBySkuId();
          }
          if(this.title === '违规标记' && record.violationTag){
            record.violationTag.level = +record.violationTag.level;
            this.model_ = Object.assign({}, record.violationTag);
          }
          if(this.title === '上传视频' || this.title === '下载视频'){
            this.$set(this.model_, 'video', record.video);
          }
          if(this.title === '备注'){
            this.$set(this.model_, 'remark', record.remark);
          }
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            let httpurl = '';
            let method = '';
            let params = Object.assign({}, this.model_);
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              if(this.title === '导出'){
                if(that.model_.type === 2){
                  that.model_.exportCount = '';
                }else{
                  if(!this.model_.exportCount){
                    this.$message.warning('请输入导出条数!');
                    return;
                  }
                }
                // 图片排序
                let imgTypeList = ['effectImageList', 'whiteBackgroundImageList', 'sizeImageList', 'otherImageList', 'elementImageList'];
                params.skuImageId.sort(function(a, b){
                  let aRecord = that.productImg.find(item => item.id === a);
                  let bRecord = that.productImg.find(item => item.id === b);
                  return imgTypeList.indexOf(aRecord.customImgType) - imgTypeList.indexOf(bRecord.customImgType);
                })
                params.skuImageId = params.skuImageId.join(',')
                params.skuId = this.model.id;
                this.handleExportXls('SKU列表', this.url.exportSKU, params, () => {
                  that.$emit('ok');
                });
                return;
              }else if(this.title === '备注'){
                httpurl+=this.url.updateRemark;
                method = 'post';
                params = {
                  remark: this.model_.remark,
                  skuId: this.model.id
                }
              }else if(this.title === '上传视频'){
                httpurl+=this.url.uploadVideo;
                method = 'post';
                params = {
                  video: this.model_.video,
                  skuId: this.model.id
                }
              }else if(this.title === '违规标记'){
                httpurl+=this.url.violationMark;
                method = 'post';
                params = {
                  level: this.model_.level,
                  tagId: this.model_.tagId,
                  reason: this.model_.reason,
                  skuId: this.model.id
                }
              }else if(this.title === '下载视频'){
                this.handleDownVideo();
                return;
              }
            }
            that.confirmLoading = true;
            httpAction(httpurl, params,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      async handleDownVideo(){
        if(!(this.checkedList && this.checkedList.length)){
          this.$message.warning('请选择要下载的视频!');
          return;
        }
        const blob = await this.getImgArrayBuffer(this.checkedList);
        const a = document.createElement('a');
        document.body.appendChild(a)
        a.style.display = 'none'
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = '视频.mp4';
        a.click();
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url);
        this.$emit('ok');
      },
      async getImgArrayBuffer(url) {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        return await response.blob();
      },
      handleImg(src){
        if(src){
          this.$viewerApi({images: [src]});
        }
      },
      queryBySkuId(){
        getAction(this.url.queryBySkuId, { skuId: this.model.id }).then((res) => {
          if(res.success){
            let productImg = res.result || {};
            let keyList = Object.keys(productImg);
            keyList.forEach(item => {
              if(item === 'effectImageList' || item === 'elementImageList' || item === 'otherImageList' || item === 'sizeImageList' || item === 'whiteBackgroundImageList' ){
                if(!(productImg[item] && productImg[item].length)) return;
                productImg[item] = productImg[item].map(cur => {
                  return {
                    ...cur,
                    customImgType: item
                  }
                })
                this.productImg = [...this.productImg, ...productImg[item]];
              }
            })
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      getTagList(){
        let params = {
          type: 1,
          column: 'createTime',
          order: 'desc',
          pageNo: 1,
          pageSize: 9999
        }
        getAction(this.url.tagList, params).then((res) => {
          if(res.success){
            let tagOptions = (res.result && res.result.records) || [];
            this.tagOptions = tagOptions.map(item => {
              return {
                text: item.name,
                value: item.id
              }
            })
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      productLibrarySkuMskuList(){
        this.queryParam = {
          skuId: this.model.id
        }
        this.loadData();
      },
      handleEdit(record){
        this.mskuObj = {
          visible: true,
          record: Object.assign({}, record)
        }
      },
      handleOk(){
        if(!this.mskuObj.record.msku){
          this.$message.warning('请输入MSKU');
          return;
        }
        let params = {
          msku: this.mskuObj.record.msku,
          sku: this.mskuObj.record.sku,
          skuId: this.model.id,
          id: this.mskuObj.record.id
        }
        putAction(this.url.productLibrarySkuMskuEdit, params).then((res) => {
          if(res.success){
            this.$message.success(res.message);
            this.productLibrarySkuMskuList();
            this.mskuObj.visible = false;
          }else{
            this.$message.warning(res.message)
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
.export-img{
  img{
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
  }
  p{
    text-align: center;
    font-size: 12px;
    margin-top: 4px;
  }
  /deep/.ant-checkbox-wrapper{
    position: relative;
    .ant-checkbox{
      position: absolute;
      left: 0;
      top: 0;
    }
    .ant-checkbox + span{
      padding: 0;
    }
  }
}
/deep/.input-table .scroll-view{
  pointer-events: auto;
}
/deep/.j-table-force-nowrap, /deep/.jeecg-form-container-disabled .ant-select{
  pointer-events: auto;
  cursor: auto;
}
.video-custom{
  width: 100%;
  /deep/.ant-upload{
    display: block;
  }
  /deep/.file-list-box:nth-child(4n + 2){
    margin: 4px 4px 4px 0;
  }
  /deep/.file-list-box{
    float: left;
    width: calc((100% - 60px) / 4);
  }
}
.download-video{
  width: 100%;
  /deep/.file-list-box{
    margin: 4px 20px;
    width: calc((100% - 130px) / 4);
    .ant-radio{
      position: absolute;
      left: -28px;
      top: -8px;
    }
  }
}
</style>